from django.shortcuts import render, redirect, HttpResponse
from utils.sql_helper import exec_sql
import json


def model_add_student(request):
    ret = {"status":True, "msg":None}
    try:
        sname = request.POST.get("sname")
        class_id = request.POST.get("class_id")
        exec_sql(f'insert into student (sname, class_id) values ("{sname}",{class_id})', is_modify=True)
    except Exception as e:
        ret["status"] = False
        ret["msg"] = str(e)
    return HttpResponse(json.dumps(ret))


def model_edit_student(request):
    ret = {"status": True, "msg": None}
    try:
        sid = request.POST.get("sid")
        sname = request.POST.get("sname")
        class_id = request.POST.get("class_id")
        exec_sql(f'update student set sname ="{sname}", class_id={int(class_id)} where id = {int(sid)}', is_modify=True)
    except Exception as e:
        ret["status"] = False
        ret["msg"] = str(e)
    return HttpResponse(json.dumps(ret))


def model_del_student(request):
    ret = {"status":True, "msg":None}
    try:
        sid = request.POST.get("sid")
        exec_sql(f'delete from student where id = {sid}', is_modify=True)
    except Exception as e:
        ret["status"] = False
        ret["msg"] = str(e)
    return HttpResponse(json.dumps(ret))


def js_get_class_list(request):
    class_list = exec_sql('select id, cname from class', is_get_list=True)
    return HttpResponse(json.dumps(class_list))


def js_get_one_student(request):
    sid = request.GET.get("sid")
    one_student = exec_sql(f'select id, sname, class_id from student where id={sid}', is_get_one=True)
    one_class = exec_sql(f'select cname from class where id = (select class_id from student where id = {sid})', is_get_one=True)
    class_list = exec_sql(f'select id, cname from class', is_get_list=True)
    ret = {"one_student":one_student, "one_class":one_class, "class_list":class_list}
    print(ret)
    return HttpResponse(json.dumps(ret))
